package com.hunliji.monitor.web.facade.impl;

import com.alibaba.fastjson.JSON;
import com.hunliji.monitor.service.api.ConsumeService;
import com.hunliji.monitor.service.api.ZdxConsumeService;
import com.hunliji.monitor.service.api.model.bo.WalletConsumeBO;
import com.hunliji.monitor.service.api.model.bo.ZdxConsumeBO;
import com.hunliji.monitor.service.api.model.param.QueryWalletConsumeParam;
import com.hunliji.monitor.service.api.model.param.QueryZdxConsumeParam;
import com.hunliji.monitor.share.component.apollo.AdvertiseBusinessConfig;
import com.hunliji.monitor.share.utils.DateCommonUtil;
import com.hunliji.monitor.web.facade.AdvertiseConsumeFacade;
import com.hunliji.monitor.web.model.bo.CurrentAndYesterdayConsumeBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 广告消耗相关
 * @author wuchen
 */
@Service
public class AdvertiseConsumeFacadeImpl implements AdvertiseConsumeFacade {

    private static final Logger logger = LoggerFactory.getLogger(AdvertiseConsumeFacadeImpl.class);
    @Resource
    private ConsumeService consumeService;
    @Resource
    private ZdxConsumeService zdxConsumeService;
    @Resource
    private AdvertiseBusinessConfig advertiseBusinessConfig;
    /**
     * 精确到小数点后6位
     */
    private static final Integer SCALE = 6;
    /**
     * 10分钟有多少秒
     */
    private static final Integer TEN_MINUTE_SECOND = 600;




    /**
     * 设置线索通10分钟窗口期的消耗情况数据
     * @param currentAndYesterdayConsumeBO
     * @param currentDate
     * @param yesterdayDate
     * @param second 查询的时间区间，默认是一天
     */
    private void setXstTodayAndTenConsume(CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO,Date currentDate,Date yesterdayDate,Integer second){
        Date currentStartDate = null;
        Date yesterdayStartDate = null;
        if(Objects.nonNull(second)){
            currentStartDate = DateCommonUtil.getBeforeSecondCurrent(currentDate,second);
            yesterdayStartDate = DateCommonUtil.getBeforeSecondCurrent(yesterdayDate,second);
        }
        //获取当天的消耗
        WalletConsumeBO currentWalletConsumeBO = queryConsume(currentStartDate,currentDate);
        //获取昨天的消耗
        WalletConsumeBO yesterdayWalletConsumeBO = queryConsume(yesterdayStartDate,yesterdayDate);
        //计算今天和昨天的消耗比
        Long currentConsume = currentWalletConsumeBO.getConsume();
        Long yesterdayConsume = yesterdayWalletConsumeBO.getConsume();
        BigDecimal yesterdayAndCurrentRatio = new BigDecimal("1");
        if(yesterdayConsume != 0 ){
            yesterdayAndCurrentRatio = new BigDecimal(currentConsume - yesterdayConsume).divide(new BigDecimal(yesterdayConsume),SCALE,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.00"));
        }
        currentAndYesterdayConsumeBO.setQueryTime(currentDate.getTime());
        currentAndYesterdayConsumeBO.setCurrentConsume(currentConsume);
        currentAndYesterdayConsumeBO.setCurrentTimeStamp(currentDate.getTime());
        currentAndYesterdayConsumeBO.setYesterdayConsume(yesterdayConsume);
        currentAndYesterdayConsumeBO.setYesterdayTimestamp(yesterdayDate.getTime());
        currentAndYesterdayConsumeBO.setYesterdayAndCurrentRatio(yesterdayAndCurrentRatio);
    }


    /**
     * 设置智多星10分钟窗口期的消耗情况数据
     * @param currentAndYesterdayConsumeBO
     * @param currentDate
     * @param yesterdayDate
     */
    private void setZdxTodayAndTenConsume(CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO,Date currentDate,Date yesterdayDate,Integer second){
        Date currentStartDate = null;
        Date yesterdayStartDate = null;
        if(Objects.nonNull(second)){
            currentStartDate = DateCommonUtil.getBeforeSecondCurrent(currentDate,second);
            yesterdayStartDate = DateCommonUtil.getBeforeSecondCurrent(yesterdayDate,second);
        }
        //获取上一个10分钟的消耗
        ZdxConsumeBO currentZdxConsumeBO = queryZdxConsumeByRecord(currentStartDate,currentDate);
        //获取20分钟前的10分钟消耗
        ZdxConsumeBO yesterdayZdxConsumeBO = queryZdxConsumeByRecord(yesterdayStartDate,yesterdayDate);
        //计算消耗比
        BigDecimal currentConsume = currentZdxConsumeBO.getSumValueConsume();
        BigDecimal yesterdayConsume = yesterdayZdxConsumeBO.getSumValueConsume();
        BigDecimal yesterdayAndCurrentRatio = new BigDecimal("1");
        if(yesterdayConsume.longValue() != 0 ){
            yesterdayAndCurrentRatio = (currentConsume.subtract(yesterdayConsume)).divide(yesterdayConsume,SCALE,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.00"));
        }
        currentAndYesterdayConsumeBO.setQueryTime(currentDate.getTime());
        currentAndYesterdayConsumeBO.setZdxCurrentConsume(currentConsume.longValue());
        currentAndYesterdayConsumeBO.setZdxCurrentTimeStamp(currentDate.getTime());
        currentAndYesterdayConsumeBO.setZdxYesterdayConsume(yesterdayConsume.longValue());
        currentAndYesterdayConsumeBO.setZdxYesterdayTimestamp(yesterdayDate.getTime());
        currentAndYesterdayConsumeBO.setZdxYesterdayAndCurrentRatio(yesterdayAndCurrentRatio);
    }


    /**
     * 设置线索通的消耗情况
     * @param currentAndYesterdayConsumeBO
     * @param currentDate
     * @param yesterdayDate
     * @param second 查询的时间区间，默认是一天
     */
    private void setXstTodayAndYesterdayConsume(CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO,Date currentDate,Date yesterdayDate,Integer second){
        Date currentStartDate = null;
        Date yesterdayStartDate = null;
        if(Objects.nonNull(second)){
            currentStartDate = DateCommonUtil.getBeforeSecondCurrent(currentDate,second);
            yesterdayStartDate = DateCommonUtil.getBeforeSecondCurrent(yesterdayDate,second);
        }
        //获取当天的消耗
        WalletConsumeBO currentWalletConsumeBO = queryConsume(currentStartDate,currentDate);
        //获取昨天的消耗
        WalletConsumeBO yesterdayWalletConsumeBO = queryConsume(yesterdayStartDate,yesterdayDate);
        //计算今天和昨天的消耗比
        Long currentConsume = currentWalletConsumeBO.getConsume();
        Long yesterdayConsume = yesterdayWalletConsumeBO.getConsume();
        BigDecimal yesterdayAndCurrentRatio = new BigDecimal("1");
        if(yesterdayConsume != 0 ){
            yesterdayAndCurrentRatio = new BigDecimal(currentConsume - yesterdayConsume).divide(new BigDecimal(yesterdayConsume),SCALE,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.00"));
        }
        currentAndYesterdayConsumeBO.setQueryTime(currentDate.getTime());
        currentAndYesterdayConsumeBO.setCurrentConsume(currentConsume);
        currentAndYesterdayConsumeBO.setCurrentTimeStamp(currentDate.getTime());
        currentAndYesterdayConsumeBO.setYesterdayConsume(yesterdayConsume);
        currentAndYesterdayConsumeBO.setYesterdayTimestamp(yesterdayDate.getTime());
        currentAndYesterdayConsumeBO.setYesterdayAndCurrentRatio(yesterdayAndCurrentRatio);
    }

    /**
     * 设置智多星的消耗情况
     * @param currentAndYesterdayConsumeBO
     * @param currentDate
     * @param yesterdayDate
     */
    private void setZdxTodayAndYesterdayConsume(CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO,Date currentDate,Date yesterdayDate,Integer second){
        Date currentStartDate = null;
        Date yesterdayStartDate = null;
        if(Objects.nonNull(second)){
            currentStartDate = DateCommonUtil.getBeforeSecondCurrent(currentDate,second);
            yesterdayStartDate = DateCommonUtil.getBeforeSecondCurrent(yesterdayDate,second);
        }
        //获取当天的消耗
        ZdxConsumeBO currentZdxConsumeBO = queryZdxConsume(currentStartDate,currentDate);
        //获取昨天的消耗
        ZdxConsumeBO yesterdayZdxConsumeBO = queryZdxConsume(yesterdayStartDate,yesterdayDate);
        //计算今天和昨天的消耗比
        BigDecimal currentConsume = currentZdxConsumeBO.getSumValueConsume();
        BigDecimal yesterdayConsume = yesterdayZdxConsumeBO.getSumValueConsume();
        BigDecimal yesterdayAndCurrentRatio = new BigDecimal("1");
        if(yesterdayConsume.longValue() != 0 ){
            yesterdayAndCurrentRatio = (currentConsume.subtract(yesterdayConsume)).divide(yesterdayConsume,SCALE,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.00"));
        }
        currentAndYesterdayConsumeBO.setQueryTime(currentDate.getTime());
        currentAndYesterdayConsumeBO.setZdxCurrentConsume(currentConsume.longValue());
        currentAndYesterdayConsumeBO.setZdxCurrentTimeStamp(currentDate.getTime());
        currentAndYesterdayConsumeBO.setZdxYesterdayConsume(yesterdayConsume.longValue());
        currentAndYesterdayConsumeBO.setZdxYesterdayTimestamp(yesterdayDate.getTime());
        currentAndYesterdayConsumeBO.setZdxYesterdayAndCurrentRatio(yesterdayAndCurrentRatio);
    }

    /**
     * 按天级别查询今天和昨天的消耗 同比
     */
    @Override
    public void logTodayAndYesterdayConsume() {
        //查询今天
        Date currentDate = new Date();
        //获取到昨天的同一时刻
        Date yesterdayDate = DateCommonUtil.getBeforeDayCurrent(currentDate,1);
        CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO = new CurrentAndYesterdayConsumeBO();

        //设置线索通的消耗
        try {
            setXstTodayAndYesterdayConsume(currentAndYesterdayConsumeBO,currentDate,yesterdayDate,null);
        }catch (Exception e){
            logger.error("线索通消耗查询异常",e);
        }
        logger.info("monitor 打印线索通消耗：{}", JSON.toJSONString(currentAndYesterdayConsumeBO));
        try {
            setZdxTodayAndYesterdayConsume(currentAndYesterdayConsumeBO,currentDate,yesterdayDate,null);
        }catch (Exception e){
            logger.error("智多星消耗查询异常",e);
        }
        logger.info("monitor 广告消耗：{}",JSON.toJSONString(currentAndYesterdayConsumeBO));
    }

    /**
     * 今日近10分钟消耗和昨天同一时间的消耗
     */
    @Override
    public void logNearTenMinuteTodayAndYesterdayConsume() {
        //查询今天
        Date currentDate = new Date();
        //获取到昨天的同一时刻
        Date yesterdayDate = DateCommonUtil.getBeforeDayCurrent(currentDate,1);
        CurrentAndYesterdayConsumeBO currentAndYesterdayConsumeBO = new CurrentAndYesterdayConsumeBO();

        //设置线索通的消耗
        try {
            setXstTodayAndYesterdayConsume(currentAndYesterdayConsumeBO,currentDate,yesterdayDate,TEN_MINUTE_SECOND);
        }catch (Exception e){
            logger.error("线索通消耗查询异常",e);
        }
        try {
            setZdxTodayAndYesterdayConsume(currentAndYesterdayConsumeBO,currentDate,yesterdayDate,TEN_MINUTE_SECOND);
        }catch (Exception e){
            logger.error("智多星消耗查询异常",e);
        }
        logger.info("monitor 今日近10分钟消耗和昨天同一时间的消耗：{}",JSON.toJSONString(currentAndYesterdayConsumeBO));


        CurrentAndYesterdayConsumeBO currentAndTenConsumeBO = new CurrentAndYesterdayConsumeBO();
        //获取到昨天的同一时刻
        Date tenDate = DateCommonUtil.getBeforeSecondCurrent(currentDate,600);
        //当天10分钟窗口比较设置线索通的消耗
        try {
            setXstTodayAndTenConsume(currentAndTenConsumeBO,currentDate,tenDate,TEN_MINUTE_SECOND);
            logger.info("monitor 近10分钟消耗和上一个10分钟的消耗：{}",JSON.toJSONString(currentAndTenConsumeBO));
        }catch (Exception e){
            logger.error("10分钟线索通消耗查询异常",e);
        }
        try {
            CurrentAndYesterdayConsumeBO zdxCurrentAndTenConsumeBO = new CurrentAndYesterdayConsumeBO();

            setZdxTodayAndTenConsume(zdxCurrentAndTenConsumeBO,currentDate,tenDate,TEN_MINUTE_SECOND);
            logger.info("monitor 智多星近10分钟消耗和上一个10分钟的消耗：{}",JSON.toJSONString(zdxCurrentAndTenConsumeBO));
        }catch (Exception e){
            logger.error("10分钟智多星消耗查询异常",e);
        }
    }

    /**
     * 查询消耗
     * @param startDate
     * @param endDate
     * @return
     */
    private WalletConsumeBO queryConsume(Date startDate,Date endDate){
        if(Objects.isNull(startDate)){
            startDate = DateCommonUtil.getDayBegin(endDate);
        }
        //查询今天的消耗
        QueryWalletConsumeParam queryWalletConsumeParam = new QueryWalletConsumeParam();
        queryWalletConsumeParam.setQueryStartTime(startDate);
        queryWalletConsumeParam.setQueryEndTime(endDate);
        queryWalletConsumeParam.setExcludeMerchantIdList(advertiseBusinessConfig.getExcludeMerchantIdList());
        List<WalletConsumeBO> walletConsumeBOList = consumeService.query(queryWalletConsumeParam);
        if(!CollectionUtils.isEmpty(walletConsumeBOList)){
            return walletConsumeBOList.get(0);
        }else {
            return emptyConsume();
        }
    }

    /**
     * 查询消耗
     * @param startDate
     * @param endDate
     * @return
     */
    private ZdxConsumeBO queryZdxConsume(Date startDate,Date endDate){
        if(Objects.isNull(startDate)){
            startDate = DateCommonUtil.getDayBegin(endDate);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询今天的消耗
        QueryZdxConsumeParam queryZdxConsumeParam = new QueryZdxConsumeParam();
        queryZdxConsumeParam.setQueryStartTime(startDate);
        queryZdxConsumeParam.setQueryEndTime(endDate);
        queryZdxConsumeParam.setExcludeMerchantIdList(advertiseBusinessConfig.getExcludeMerchantIdList());
        String dateFormat = sdf.format(endDate);
        queryZdxConsumeParam.setBizDay(dateFormat);
        List<ZdxConsumeBO> walletConsumeBOList = zdxConsumeService.query(queryZdxConsumeParam);
        if(!CollectionUtils.isEmpty(walletConsumeBOList)){
            return walletConsumeBOList.get(0);
        }else {
            return emptyZdxConsume();
        }
    }

    private ZdxConsumeBO queryZdxConsumeByRecord(Date startDate,Date endDate){
        if(Objects.isNull(startDate)){
            startDate = DateCommonUtil.getDayBegin(endDate);
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询今天的消耗
        QueryZdxConsumeParam queryZdxConsumeParam = new QueryZdxConsumeParam();
        queryZdxConsumeParam.setQueryStartTime(startDate);
        queryZdxConsumeParam.setQueryEndTime(endDate);
        queryZdxConsumeParam.setExcludeMerchantIdList(advertiseBusinessConfig.getExcludeMerchantIdList());
//        String dateFormat = sdf.format(endDate);
//        queryZdxConsumeParam.setBizDay(dateFormat);
        List<ZdxConsumeBO> walletConsumeBOList = zdxConsumeService.generalQueryByRecord(queryZdxConsumeParam);
        if(!CollectionUtils.isEmpty(walletConsumeBOList)){
            return walletConsumeBOList.get(0);
        }else {
            return emptyZdxConsume();
        }
    }

    /**
     * 获取一个空的消耗对象
     * @return
     */
    private WalletConsumeBO emptyConsume(){
        WalletConsumeBO walletConsumeBO = new WalletConsumeBO();
        walletConsumeBO.setConsume(0L);
        return walletConsumeBO;
    }

    /**
     * 获取一个空的消耗对象-智多星
     * @return
     */
    private ZdxConsumeBO emptyZdxConsume(){
        ZdxConsumeBO zdxConsumeBO = new ZdxConsumeBO();
        zdxConsumeBO.setSumValueConsume(new BigDecimal(0));
        return zdxConsumeBO;
    }
}
